package com.ykt.job;

import com.ykt.common.constant.ValueConstants;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.model.Order;

import java.util.Date;

/**
 * @author long.hua
 * @version 1.0.0
 * @since 2016-04-10 16:07
 */
public class OrderJob implements Runnable{

    private Order orderDao = Order.dao;

    @Override
    public void run() {
        updateMerchantUnconfirmedOrder();
        updateUserUnpaymentOrder();
    }

    private void updateMerchantUnconfirmedOrder(){
        int pageNo = 1;
        int pageSize = 50;
        int intervalTime = 1000 * 3600 * 24;

        PageParam<String> param = new PageParam<>();
        param.setP(Order.Status.MERCHANT_UNCONFIRMED.name());
        param.setOffset(PageData.calcOffset(pageNo, ValueConstants.PAGE_SIZE));
        param.setPageSize(pageSize);

        PageData<Order> pageData = orderDao.pageFindByStatus(param);
        while(pageData.getPageData() != null && pageData.getPageData().size() > 0){

            for (Order order : pageData.getPageData()) {
                if(new Date().getTime() - order.getCreatedTime().getTime() > intervalTime){
                    order.set("status", Order.Status.CANCEL.name()).update();
                }
            }

            pageData = orderDao.pageFindByStatus(param);
        }
    }


    private void updateUserUnpaymentOrder(){
        int pageNo = 1;
        int pageSize = 50;
        int intervalTime = 1000 * 3600 * 24 * 3;

        PageParam<String> param = new PageParam<>();
        param.setP(Order.Status.USER_UNPAYMENT.name());
        param.setOffset(PageData.calcOffset(pageNo, ValueConstants.PAGE_SIZE));
        param.setPageSize(pageSize);

        PageData<Order> pageData = orderDao.pageFindByStatus(param);
        while(pageData.getPageData() != null && pageData.getPageData().size() > 0){

            for (Order order : pageData.getPageData()) {
                if(new Date().getTime() - order.getCreatedTime().getTime() > intervalTime){
                    order.set("status", Order.Status.CANCEL.name()).update();
                }
            }

            pageData = orderDao.pageFindByStatus(param);
        }
    }

}
